package com.sdry.web.controller.llm;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sdry.model.llm.Cost;
import com.sdry.model.llm.Item;
import com.sdry.model.llm.Node;
import com.sdry.service.llm.CostService;
import com.sdry.service.llm.ItemService;
import com.sdry.utils.ResponseUtil;
import com.sdry.utils.StringUtil;

import net.sf.json.JSONObject;

/**
 * 成本费用报表
 * @author llm
 * @date 2019年7月15日
 * @version 1.0
 */
@Controller
@RequestMapping("/costReport")
public class CostReportController {
	
	@Resource ItemService itemService;
	@Resource CostService costService;
	
	/** 
	 * 进入页面
	 * @param model
	 * @return 页面路径
	*/
	@RequestMapping("/page")
	public ModelAndView pageCost (Model model) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/llm/report");
		return mv;
	}
	
	/**
	 * 财务报表
	 */
	@RequestMapping("reslist")
    public void getReslist(HttpServletRequest request,HttpServletResponse response){

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "no");
        Node tree = getTreeJson();//获得树形结构的json数据
        Node n = tree.zxPraseTree(tree);//把树形结构数据按中序遍历顺序，加入list
        List<Node> reslist = n.getNodes();//获得上面的list
        List<Node> list = new ArrayList<Node>();
        for(Node node : reslist) {//去掉null节点
            if(null != node) {
                if(node.getId() != null) {
                    list.add(node);
                }
            }
        }
        jsonObject.put("result", "ok");
	    jsonObject.put("data", list);
        try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

     public Node getTreeJson() {
         List<Item> reslist = itemService.queryAllByMution(null); //从数据库加载所有数据，得到list
         List<Node> nodes = new ArrayList<Node>();
         Cost param = new Cost();
         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
         String time = format.format(new Date());
         for(Item res : reslist){
        	 float monthMoney = 0L;
        	 float yearMoney = 0L;
             Node node = new Node();
             //如果只有项目结构只有两级的金额算法
             //模糊查询本月所有数据，金额累加
             /*param.setItemId(res.getId());
             param.setCreateDate(time.substring(0, 7));
             List<Cost> listMonth = costService.queryAllByMution(param);
             for(Cost c : listMonth){
            	 monthMoney = StringUtil.calcFloatValue(monthMoney, Float.valueOf(c.getCostMoney()), "add");
             }*/
             //模糊查询本月所有数据，金额累加
             /*param.setCreateDate(time.substring(0, 4));
             List<Cost> listYear = costService.queryAllByMution(param);
             for(Cost c : listYear){
            	 yearMoney = StringUtil.calcFloatValue(yearMoney, Float.valueOf(c.getCostMoney()), "add");
             }*/
             //如果项目结构不限制层级，用递归的算法
             List<Long> list = new ArrayList<>();
             list.add(res.getId());
             monthMoney = getSum(list, 0L, time.substring(0, 7));
             yearMoney = getSum(list, 0L, time.substring(0, 4));
             node.setMonthMoney(monthMoney);
             node.setYearMoney(yearMoney);
             node.setId(res.getId());
             node.setFid(res.getParentId());
             node.setCname(res.getItemName());
             nodes.add(node);
             node = null;
         }
         Node tree = new Node();
         Node mt = tree.createTree(nodes);//把list转化成tree
         //System.out.println(tree.iteratorTree(mt));//遍历打印
         return mt;
     }
     
     public float getSum(List<Long> ids, float sumMoney, String time){
    	 List<Long> paramList = new ArrayList<>();
    	 Cost param = new Cost();
    	 Item item = new Item();
    	 param.setCreateDate(time);
         for(Long id : ids){
        	 param.setItemId(id);
        	 //查出当前节点的金额
        	 List<Cost> listMonth = costService.queryAllByMution(param);
        	 if(listMonth.size() > 0){
        		 sumMoney =  StringUtil.calcFloatValue(Float.valueOf(listMonth.get(0).getCostMoney()), sumMoney, "add");
        	 }else{
        		 sumMoney = sumMoney + 0F;
        	 }
        	 item.setParentId(id);
        	 List<Item> list = itemService.queryAllByMution(item);
        	 if(list.size() > 0){
        		 for(Item it : list){
        			 paramList.add(it.getId());
        		 }
        	 }
         }
         if(paramList.size() > 0){
        	 return getSum(paramList, sumMoney, time);
         }else{
        	 return sumMoney;
         }
     }
     
}
